package com.konsung.ui;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.util.Log;

import com.konsung.provide.ProviderReader;
import com.konsung.util.UiUtils;
import com.konsung.util.constant.GlobalConstant;
import com.squareup.leakcanary.LeakCanary;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.List;

/**
 * 进程启动
 */
public class MyApplication extends Application {
    private static Context context; //全局上下文
    @Override
    public void onCreate() {
        super.onCreate();
        UiUtils.initData(this);

        context = getApplicationContext();
        String packageName = getPackageName();
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        // 获取当前进程名
        String processName = null;
        List<ActivityManager.RunningAppProcessInfo> appList = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo info : appList) {
            if (info.pid == android.os.Process.myPid()) {
                processName = info.processName;
            }
        }
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(context);
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        // 初始化Bugly
        CrashReport.initCrashReport(context, GlobalConstant.APPID, isApkDebugable(), strategy);
        CrashReport.setUserId(ProviderReader.getDeviceCode(this) + "_" + android.os.Build.SERIAL);
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
    }

    /**
     * 静态获取全局上下文
     * @return 上下文
     */
    public static Context getContext() {
        return context;
    }

    /**
     * 当我们没在AndroidManifest.xml中设置其debug属性时:
     * 使用Eclipse运行这种方式打包时其debug属性为true,使用Eclipse导出这种方式打包时其debug属性为false.
     * 在使用ant打包时，其值就取决于ant的打包参数是release还是debug.
     * 因此在AndroidMainifest.xml中最好不设置android:debuggable属性置，而是由打包方式来决定其值.
     * @return true, 程序为debug版本；false,程序为release版本
     */
    private boolean isApkDebugable() {
        try {
            ApplicationInfo info = getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            Log.e("HealthOne", "Apk debugable check failed!");
        }
        return false;
    }
}
